const app = getApp()
import { getClassAndStyleList, saveFile, saveIslandMaterialBook, saveMaterialBook } from '../../../../api/index'
const uploadOss = require('../../../../utils/upload/uploadImg.js')
import { uuid } from '../../../../utils/util'

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },
  data: {
    showAddressPop: false,
    showCatePop: false,
    currentDiyItem: {
      materialCoverUrl: '',
      supplierName: '',
      headOfSales: '',
      address: '',
      headOfSalesPhone: '',
      materialName: '',
      code: '',
      appliedArea: '',
      typeExplain: '',
      color: '',
      surfaceTreatment: '',
      avoidFireRequire: '',
      classificationId: '',
      classificationStr: '',
      coverFileId: '',
      sizeFileId: '',
      dynamicArray: [],
      explainArray: [],
      coverFileManage: {
        fileUrl: ''
      },
      fileManage: {
        fileUrl: ''
      }
    },
    coverFileManage: [],
    fileManage: [],
    cateList: [],
    dynamicLabel: '',
    dynamicValue: '',
    explainLabel: '',
    explainValue: '',
  },
  methods: {
    cancel () {
      this.triggerEvent('close')
    },
    save () {
      if (!this.data.currentDiyItem.materialName) {
        wx.showToast({ title: '请先输入材料名称！', icon: 'none' })
        return
      }
      if (!this.data.currentDiyItem.classificationId) {
        wx.showToast({ title: '请先选择材料分类！', icon: 'none' })
        return
      }
      if (!this.data.currentDiyItem.coverFileId) {
        wx.showToast({ title: '请先上传材料照片！', icon: 'none' })
        return
      }
      const uid = uuid()
      this.data.currentDiyItem.uid = uid
      if (this.data.currentDiyItem.address && this.data.currentDiyItem.detailAddress) {
        this.data.currentDiyItem.address = this.data.currentDiyItem.address + this.data.currentDiyItem.detailAddress
      }
      this.triggerEvent('add', this.data.currentDiyItem)
    },
    changeInput ({ currentTarget: { dataset: { key } }, detail }) {
      this.setData({ ['currentDiyItem.' + key]: detail.value })
    },
    changeaAttrInput ({ currentTarget: { dataset: { key } }, detail }) {
      this.setData({ [key]: detail.value })
    },
    addDynamicArray () {
      if (!this.data.dynamicLabel) {
        wx.showToast({ title: '请输入要添加的属性名称！', icon: 'none' })
        return
      }
      this.data.currentDiyItem.dynamicArray.push({ paramName: this.data.dynamicLabel, paramValue: this.data.dynamicValue })
      this.setData({ 'currentDiyItem.dynamicArray': this.data.currentDiyItem.dynamicArray, dynamicLabel: '', dynamicValue: '' })
    },
    addExplainArray () {
      if (!this.data.explainLabel) {
        wx.showToast({ title: '请输入要添加的属性名称！', icon: 'none' })
        return
      }
      this.data.currentDiyItem.explainArray.push({ paramName: this.data.explainLabel, paramValue: this.data.explainValue })
      this.setData({ 'currentDiyItem.explainArray': this.data.currentDiyItem.explainArray, explainValue: '', explainValue: '' })
    },
    deleteItem ({ currentTarget: { dataset: { key, index } } }) {
      this.data.currentDiyItem[key].splice(index, 1)
      this.setData({ ['currentDiyItem.' + key]: this.data.currentDiyItem[key] })
    },
    selectAddress () {
      this.setData({ showAddressPop: true })
    },
    closeAddress () {
      this.setData({ showAddressPop: false })
    },
    confirmAddress ({ detail }) {
      this.setData({ 'currentDiyItem.address': `${detail[0].label}${detail[1].label}${detail[2].label}`, showAddressPop: false })
    },
    changeCate ({ detail }) {
      console.log(detail)
      this.setData({ 'currentDiyItem.classificationId': this.data.cateList[detail.value].classificationId, 'currentDiyItem.classificationStr': this.data.cateList[detail.value].classificationName })
    },
    deleteTempFile ({ currentTarget: { dataset: { key, index } } }) {
      this.data[key].splice(index, 1)
      this.setData({ [key]: this.data[key] })
    },
    deleteFile ({ currentTarget: { dataset: { key, index } } }) {
      this.data.currentDiyItem[key] = {}
      if (key === 'coverFileManage') {
        this.setData({ 'currentDiyItem.materialCoverUrl': '' })
      }
      this.setData({ ['currentDiyItem.' + key]: {} })
    },
    async againUpload ({ target: { dataset: { key, item, index } } }) {
      let _this = this
      let tempFiles = this.data[key]
      tempFiles[index].success = ''
      _this.setData({
        [key]: tempFiles
      })
      const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
      if (file) {
        const { ResultSet } = await saveFile({
          fileList: [{
            fileSize: item.size,
            fileName: file.fileName,
            fileUrl: file.fileUrl
          }]
        })
        tempFiles.splice(index, 1)
        _this.data.currentDiyItem[key] = {
          uuid: item.uuid,
          fileId: ResultSet.userData.fileIdList[0].fileId,
          fileName: file.fileName,
          fileUrl: ResultSet.userData.fileIdList[0].url,
          url: ResultSet.userData.fileIdList[0].fileUrl
        }
      } else {
        tempFiles[index].success = 1
        _this.setData({
          fileList: tempFiles
        })
      }
      _this.setData({
        [key]: tempFiles,
        ['currentDiyItem.' + key]:  _this.data.currentDiyItem[key]
      })
      if (key === 'coverFileManage') {
        _this.setData({ 'currentDiyItem.materialCoverUrl': _this.data.currentDiyItem.coverFileManage.fileUrl, 'currentDiyItem.coverFileId': _this.data.currentDiyItem.coverFileManage.fileId })
      }
    },
    addFile ({ target: { dataset: { key, num } } }) {
      let _this = this
      wx.chooseMedia({
        count: parseInt(num),
        mediaType: ['image'],
        async success (res) {
          _this.setData({ [`currentDiyItem.${key}`]: {} })
          res.tempFiles.forEach(item => {
            item.uuid = uuid()
            item.progress = 0
          })
          _this.data[`${key}`].push(...res.tempFiles)
          _this.setData({
            [`${key}`]: _this.data[`${key}`]
          })
          let tempFiles = _this.data[`${key}`]
          let temFileList = []
          if (tempFiles.length) {
            temFileList = await Promise.all(tempFiles.map(async (item, index) => {
              const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
              if (file) {
                const { ResultSet } = await saveFile({
                  fileList: [{
                    fileSize: item.size,
                    fileName: file.fileName,
                    fileUrl: file.fileUrl
                  }]
                })
                return {
                  uuid: item.uuid,
                  fileId: ResultSet.userData.fileIdList[0].fileId,
                  fileName: file.fileName,
                  fileUrl: ResultSet.userData.fileIdList[0].url,
                  url: ResultSet.userData.fileIdList[0].fileUrl
                }
              } else {
                tempFiles[index].success = 1
                _this.setData({
                  [`${key}`]: tempFiles
                })
              }
            }))
          }
          let tempFileList = temFileList.filter(item => item)
          _this.data.currentDiyItem[key] = tempFileList[0]
          if (_this.data.currentDiyItem[key] && _this.data.currentDiyItem[key].uuid) {
            let rowIndex = tempFiles.findIndex(row => _this.data.currentDiyItem[key].uuid === row.uuid)
            if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
          }
          _this.setData({
            [`${key}`]: tempFiles,
            [`currentDiyItem.${key}`]: _this.data.currentDiyItem[key]
          })
          if (key === 'coverFileManage') {
            _this.setData({ 'currentDiyItem.materialCoverUrl': _this.data.currentDiyItem.coverFileManage.fileUrl, 'currentDiyItem.coverFileId': _this.data.currentDiyItem.coverFileManage.fileId })
          }
        }
      })
    },
    uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
      return new Promise((resolve, reject) => {
        uploadOss(item[key],
          (res) => {
            resolve(res)
          },
          (err) => {
            resolve()
          },
          files, index, that, dataKey
        )
      })
    },
    async getCateList () {
      try {
        const { ResultSet } = await getClassAndStyleList()
        this.setData({ cateList: ResultSet.userData.firstClassificationList })
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    beforeOpen () {
      this.data.currentDiyItem = {
        supplierName: '',
        headOfSales: '',
        address: '',
        headOfSalesPhone: '',
        materialName: '',
        code: '',
        appliedArea: '',
        typeExplain: '',
        color: '',
        surfaceTreatment: '',
        avoidFireRequire: '',
        classificationId: '',
        coverFileId: '',
        sizeFileId: '',
        dynamicArray: [],
        explainArray: [],
        coverFileManage: {
          fileUrl: ''
        },
        fileManage: {}
      }
      this.setData({
        currentDiyItem: this.data.currentDiyItem,
        coverFileManage: [],
        fileManage: [],
        cateList: [],
        dynamicLabel: '',
        dynamicValue: '',
        explainLabel: '',
        explainValue: ''
      })
      this.getCateList()
    }
  },
})